//
//  TTWeiBoViewModel.swift
//  NewWeiBo
//
//  Created by 吴天益 on 2017/7/26.
//  Copyright © 2017年 ttt. All rights reserved.
//

import UIKit
import YYWebImage


class TTWeiBoViewModel: NSObject {
    
    lazy var homeArray: [TTWeiBoViewModel] = [TTWeiBoViewModel]()
    
    //微博模型
    var weiBoModel: TTWeiBoModel?{
        didSet{
            
            //根据认证等级获取相应的图片
            useTheImageWithVerifiedType(verifiedType: weiBoModel?.user?.verified_type ?? -1)
            
            //根据会员等级获取相应的图片
            useTheImageWithMbRank(mbRank: weiBoModel?.user?.mbrank ?? 0)
            
            //处理被转发微博内容
            handleRetweetedContent()
            
            //处理来源字符串
            brainpowerTime = handleBrainpowerTime()
        }
    }
    
    //判断好的认证图片
    var verifiedImage: UIImage?
    //判断好的会员等级图片
    var mbrankImage: UIImage?
    //处理好转发微博内容
    var retweetedContent: String?
    //处理好的来源字符串
    var source: String?
    //时间戳处理
    var brainpowerTime: String?
    //加载了多少条微博数据
    var loadNumStr: String?
    
//    //判断是否上拉
//    var isPullUp: Bool = false
    
    //MARK: - 加载网络数据
    func loadDataWithLinPai(isPullUp: Bool = false, backClosure: @escaping (Bool)->()){
        
        
        var maxId: Int64 = 0
        var sinceId: Int64 = 0
        //判断是上拉加载还是下拉刷新
        if isPullUp {
            //上拉加载
            if let id = homeArray.last?.weiBoModel?.id {
                //会加载小于或者等于maxId的数据,所以会重复加载等于的数据,所以要-1
                maxId = id - 1
            }
        }else{
            sinceId = homeArray.first?.weiBoModel?.id ?? 0
        }

        
        TTNetWorkTool.shareTool.requestUserAndCareUsersMessageWithLinPai(linPai: (TTUserAccountViewModel.shareViewModel.userAccountModel?.access_token) ?? "",sinceId: sinceId,maxId: maxId) { (response, error) in
            if(error != nil){
                backClosure(false)
                return
            }
            
            let dict = response as! [String: Any]
            
            let arr = dict["statuses"] as! [[String: Any]]
            
            let arr2 = NSArray.yy_modelArray(with: TTWeiBoModel.self, json: arr) as! [TTWeiBoModel]
            
            //创建调度组
            let group = DispatchGroup()
            
            var arrM = [TTWeiBoViewModel]()
            for model in arr2 {
                
//                print(model.pic_urls?.count ?? 0)
                //如果是单张图片就下载下来,进调度组
                if model.pic_urls?.count == 1{
                    //获取图片url字符串
                    let imageStr = model.pic_urls?.first?.thumbnail_pic
                    
                    group.enter()
                    YYWebImageManager.shared().requestImage(with: URL(string: imageStr!)!, options: [], progress: nil, transform: nil, completion: { (image, url, _, _, error) in
                        print("原创微博单张图片下载完成")
                        //下载完成跳出调度组
                        group.leave()
                    })
                }
                if model.retweeted_status?.pic_urls?.count == 1{
                    let imageStr = model.retweeted_status?.pic_urls?.first?.thumbnail_pic
                    
                    group.enter()
                    YYWebImageManager.shared().requestImage(with: URL(string: imageStr!)!, options: [], progress: nil, transform: nil, completion: { (image, url, _, _, error) in
                        print("转发微博单张图片下载完成")
                        
                        group.leave()
                    })
                }
                
                let viewModel = TTWeiBoViewModel()
                
                viewModel.weiBoModel = model
                
                arrM.append(viewModel)
            }
            
            //加载了多少条数据的字符串处理
            if arrM.count == 0 {
                self.loadNumStr = "没有最新微博数据了"
            }else{
                self.loadNumStr = "加载了\(arrM.count)条微博数据"
            }
            
            
            //判断是上拉加载还是下拉刷新
            if isPullUp {
                //上拉加载
                self.homeArray.append(contentsOf: arrM)
            }else{
                //下拉刷新
                self.homeArray.insert(contentsOf: arrM, at: 0)
            }
 
            
            //当单张图片全部下载完后才能回调,如果没有图片要下载,group中没有任务,就会执行这其中的方法
            group.notify(queue: DispatchQueue.main, execute: { 
                
                backClosure(true)
            })
        }
    }

    //MARK: - 根据认证等级获取相应的图片
    func useTheImageWithVerifiedType(verifiedType: Int){
        
        switch verifiedType {
        case 0:
            verifiedImage = UIImage(named: "avatar_vip")
        case 2,3,5:
            verifiedImage = UIImage(named: "avatar_enterprise_vip")
        case 220:
            verifiedImage = UIImage(named: "avatar_grassroot")
        default:
            verifiedImage = nil
        }

    }
    
    //MARK: - 根据会员等级获取相应的图片
    func useTheImageWithMbRank(mbRank: Int){
        
        if mbRank>=1 && mbRank<=6 {
            
            mbrankImage = UIImage(named: "common_icon_membership_level\(mbRank)")
        }else{
            mbrankImage = UIImage(named: "common_icon_membership_expired")
        }
   
    }
    
    //MARK: - 处理好转发微博内容
    func handleRetweetedContent(){
        if let retweetedStatus = weiBoModel?.retweeted_status {
            //拼接微博内容字符串
            if let name = retweetedStatus.user?.screen_name,let text = retweetedStatus.text {
                retweetedContent = "@\(name): \(text)"
            }
        }
    }
    
    //MARK: - 截取需要的来源字符串
    func getSourceStr(){
        //"<a href=\"http://app.weibo.com/t/feed/cUcI1A\" rel=\"nofollow\">分享按钮</a>"
        
        //通过获取指定字符串在大字符串中的范围,在通过范围的尾头索引来获取其中间我们要的字符串在大字符串中的头尾索引
        if let leadRange = weiBoModel?.source?.range(of: "\">"),let trealRange = weiBoModel?.source?.range(of: "</") {
            //upperBound表示范围中最大的光标索引
            let startIndex = leadRange.upperBound
            //最小
            let endIndex = trealRange.lowerBound
            
            source = weiBoModel?.source?.substring(with: startIndex..<endIndex)
  
        }
    }
    
    //MARK: - 时间戳处理
    func handleBrainpowerTime()->(String?){
        //  1. 第一种方式可以使用DateFormatter,把时间字符串转成时间对象， 注意需要指定locale, 并且设置“en_US”
        //        let dt = DateFormatter()
        //        dt.dateFormat = "EEE MMM dd HH:mm:ss Z yyyy"
        //        dt.locale = Locale(identifier: "en_US")
        //        dt.date(from: "时间字符串")
        //  2. 使用YYModel直接把时间字符串转成时间对象

        guard let createAt = weiBoModel?.created_at else {
            return nil
        }
 
        let dt = DateFormatter()
        //  年份的格式化
        dt.dateFormat = "yyyy"
        //  获取发微博时间年份
        let createAtYear = dt.string(from: createAt)
        //  获取今年时间年份
        let currentYear = dt.string(from: Date())
        
        let isThisYear: Bool = createAtYear == currentYear
        //  代码执行到此，时间对象一定有值
        if isThisYear == true {
            //  是今年
            //  创建日历对象
            let calendar = Calendar.current
            //  是否是今天
            if calendar.isDateInToday(createAt) {
                //  今天
                //  获取时间差对应的秒数, 发微博时间距离当前时间差多少秒
                let timeInterval = abs(createAt.timeIntervalSinceNow)
                //  判断是否是1分钟之前
                if timeInterval < 60 {
                    return "刚刚"
                } else if timeInterval < 3600 {
                    //  判断是否是1小时之前的逻辑
                    let result = timeInterval / 60
                    return "\(Int(result))分钟前"
                } else {
                    //  其它时间
                    let result = timeInterval / 3600
                    return "\(Int(result))小时前"
                }
                
            } else if calendar.isDateInYesterday(createAt) {
                //  昨天
                dt.dateFormat = "昨天 HH:mm"
            } else {
                //  其它
                dt.dateFormat = "MM-dd HH:mm"
            }
        } else {
            //  不是今年
            dt.dateFormat = "yyyy-MM-dd HH:mm"
        }
        
        return dt.string(from: createAt)
    }

}
